package com.yww.leetcode.binarysearch;

/**
 * @author yww
 * @description 704. 二分查找
 * @since 2024/1/29 14:46
 */
public class BinarySearch704 {

    public int search(int[] nums, int target) {
        int res = search01(nums, target);
        res = search02(nums, target);
        res = search03(nums, target);
        return res;
    }

    //  基础
    public static int search01(int[] nums, int target) {
        int i = 0, j = nums.length - 1;
        while (i <= j) {
            int m = (i + j) >>> 1;
            if (target < nums[m]) {
                j = m - 1;
            } else if (nums[m] < target) {
                i = m + 1;
            } else {
                return m;
            }
        }
        return -1;
    }

    // [i,j)
    public static int search02(int[] nums, int target) {
        int i = 0, j = nums.length;
        while (i < j) {
            int m = (i + j) >>> 1;
            if (target < nums[m]) {
                j = m;
            } else if (nums[m] < target) {
                i = m + 1;
            } else {
                return m;
            }
        }
        return -1;
    }

    // 平衡
    public static int search03(int[] nums, int target) {
        int i = 0, j = nums.length;
        while (1 < j - i) {
            int m = (i + j) >>> 1;
            if (target < nums[m]) {
                j = m;
            } else {
                i = m;
            }
        }
        return nums[i] == target ? i : -1;
    }
}
